<?php
// +—————————————————————————————————————————————————————————————————————
// | Created by Yunbao
// +—————————————————————————————————————————————————————————————————————
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +—————————————————————————————————————————————————————————————————————
// | Author: https://gitee.com/yunbaokeji
// +—————————————————————————————————————————————————————————————————————
// | Date: 2022-03-22
// +—————————————————————————————————————————————————————————————————————

/**
 * 充值
 */

class Api_Charge extends PhalApi_Api {

	public function getRules() {
		return array(
            'getBalance' => array(
				'uid' => array('name' => 'uid', 'type' => 'int', 'desc' => '用户ID'),
				'token' => array('name' => 'token', 'type' => 'string','desc' => '用户token'),
				'type' => array('name' => 'type', 'type' => 'int','desc' => 'APP类型，1是安卓，2是IOS'),
				'version' => array('name' => 'version', 'type' => 'string','desc' => '版本号'),
			),
			'getAliOrder' => array(
				'uid' => array('name' => 'uid', 'type' => 'int', 'desc' => '用户ID'),
				'changeid' => array('name' => 'changeid', 'type' => 'int', 'desc' => '充值规则ID'),
				'coin' => array('name' => 'coin', 'type' => 'string',  'desc' => '钻石'),
				'money' => array('name' => 'money', 'type' => 'string', 'desc' => '充值金额'),
			),
			'getWxOrder' => array( 
				'uid' => array('name' => 'uid', 'type' => 'int', 'desc' => '用户ID'),
				'changeid' => array('name' => 'changeid', 'type' => 'string',  'desc' => '充值规则ID'),
				'coin' => array('name' => 'coin', 'type' => 'string',  'desc' => '钻石'),
				'money' => array('name' => 'money', 'type' => 'string', 'desc' => '充值金额'),
			),
			'updatePaymentStatus' => array( 
				'uid' => array('name' => 'uid', 'type' => 'int', 'min' => 1, 'require' => true, 'desc' => '用户ID'),
				'token' => array('name' => 'token', 'type' => 'string', 'require' => true, 'desc' => '用户token'),
				'orderid' => array('name' => 'orderid', 'type' => 'string',  'require' => true, 'desc' => '订单号'),
				'money' => array('name' => 'money', 'type' => 'string', 'require' => true, 'desc' => '充值金额'),
				'nonce' => array('name' => 'nonce', 'type' => 'string', 'require' => true, 'desc' => 'paypal支付订单号'),
				'time' => array('name' => 'time', 'type' => 'string', 'desc' => '时间戳'),
			),
			
		);
	}
	
	/**
     * braintree回调处理
     * @desc 用于braintree回调处理
     * @return int code 操作码，0表示成功
     * @return string msg 提示信息
     */
	public function updatePaymentStatus() {
		$rs = array('code' => 0, 'msg' => '', 'info' => array());
		 
        $uid=checkNull($this->uid);
		$token=checkNull($this->token);
		$orderid=checkNull($this->orderid);
		$money=checkNull($this->money);
		$nonce=checkNull($this->nonce);
		$time=checkNull($this->time);
				
		$now=time();
        if($now-$time>300){
            $rs['code']=1001;
            $rs['msg']='参数错误';
            return $rs;
        }

		$domain = new Domain_Charge();
		$info = $domain->updatePaymentStatus($uid,$nonce,$orderid,$money);
	
		if($info==1003){
			$rs['code'] = 1003;
			$rs['msg'] = '订单信息有误，请重新提交';
			return $rs;
		}
		
		

		$rs['msg']='操作成功';
		
        return $rs;
    }
    
    /**
	 * 充值规则
	 * @desc 用于获取充值规则
	 * @return int code 操作码，0表示成功， 1表示用户不存在
	 * @return array info 
	 * @return string info[].id 规则ID
	 * @return string info[].money 金额
	 * @return string info[].coin 非苹果支付钻石数
	 * @return string info[].coin_ios 苹果支付钻石数
	 * @return string info[].product_id 规则ID
	 * @return string info[].give 规则ID
	 * @return string msg 提示信息
	 */
	public function getChargeRules() {
		$rs = array('code' => 0, 'msg' => '', 'info' => array());

		$domain = new Domain_Charge();
		$info = $domain->getChargeRules();
        
        $rs['info'] =$info;
        
		return $rs;
	}
    
	/**
	 * 我的钻石
	 * @desc 用于获取用户余额,充值规则 支付方式信息
	 * @return int code 操作码，0表示成功
	 * @return array info 
	 * @return string info[0].coin 用户余额
	 * @return array  info[0].rules 充值规则
	 * @return string info[0].rules[].id 规则ID
     * @return string info[0].rules[].money 金额
	 * @return string info[0].rules[].coin 非苹果支付钻石数
	 * @return string info[0].rules[].coin_ios 苹果支付钻石数
	 * @return string info[0].rules[].product_id 苹果项目ID
	 * @return string info[0].rules[].give 赠送钻石，为0时不显示赠送
	 * @return string info[0].aliapp_partner 支付宝合作者身份ID
	 * @return string info[0].aliapp_seller_id 支付宝帐号	
	 * @return string info[0].aliapp_key 支付宝密钥PKCS8
	 * @return string info[0].wx_appid 微信APPID
     * @return array info[0].paylist 支付方式列表
     * @return string info[0].paylist[].id ali支付宝，wx微信，apple苹果
     * @return string info[0].paylist[].name 名称
     * @return string info[0].paylist[].thumb 图标
	 * @return string msg 提示信息
	 */
	public function getBalance() {
		$rs = array('code' => 0, 'msg' => '', 'info' => array());
		
        $uid=checkNull($this->uid);
        $token=checkNull($this->token);
        $type=checkNull($this->type);
        
		$checkToken=checkToken($uid,$token);
		if($checkToken==700){
			$rs['code'] = $checkToken;
			$rs['msg'] = '您的登陆状态失效，请重新登陆！';
			return $rs;
		}
		
        
		$domain = new Domain_Charge();
		$info = getUserCoin($uid);
		
        $rules= $domain->getChargeRules();

		$info['rules'] =$rules;
		
		$configpri=getConfigPri();
        $aliapp_switch=$configpri['aliapp_switch'];
        $wx_switch=$configpri['wx_switch'];
        
        $paylist=[];
        
        if($aliapp_switch){
            $paylist[]=[
                'id'=>'ali',
                'name'=>'支付宝支付',
                'thumb'=>get_upload_path("/static/app/pay/ali.png"),
            ];
        }
        
        if($wx_switch){
            $paylist[]=[
                'id'=>'wx',
                'name'=>'微信支付',
                'thumb'=>get_upload_path("/static/app/pay/wx.png"),
            ];
        }
        
        
        $info['paylist'] =$paylist;
		
		$info['aliapp_partner']=$aliapp_switch==1?$configpri['aliapp_partner']:'';
		$info['aliapp_seller_id']=$aliapp_switch==1?$configpri['aliapp_seller_id']:'';
		$info['aliapp_key']=$aliapp_switch==1?$configpri['aliapp_key']:'';
        
		$info['wx_appid']=$wx_switch==1?$configpri['wx_appid']:'';
	 
		$rs['info'][0]=$info;
		return $rs;
	}
	
	/* 获取订单号 */
	protected function getOrderid($uid){
		$orderid=$uid.'_'.date('YmdHis').rand(100,999);
		return $orderid;
	}

	/**
	 * 微信支付
	 * @desc 用于 微信支付 获取订单号
	 * @return int code 操作码，0表示成功
	 * @return array info 
	 * @return string info[0] 支付信息
	 * @return string msg 提示信息
	 */
	public function getWxOrder() {
		$rs = array('code' => 0, 'msg' => '', 'info' => array());
		
		$uid=$this->uid;
		$changeid=$this->changeid;
		$coin=checkNull($this->coin);
		$money=checkNull($this->money);

		if(!$uid || !$changeid || $coin<=0 || $money<=0){
			$rs['code']=1002;
			$rs['msg']='信息错误';
			return $rs;
		}
		
        
		$configpri = getConfigPri(); 
		$configpub = getConfigPub(); 

		 //配置参数检测
		if($configpri['wx_appid']== "" || $configpri['wx_mchid']== "" || $configpri['wx_key']== ""){
			$rs['code'] = 1002;
			$rs['msg'] = '微信未配置';
			return $rs;					 
		}

		$type=2;
        $orderid=$this->getOrderid($uid);
		
		$orderinfo=array(
			"uid"=>$uid,
			"touid"=>$uid,
			"money"=>$money,
			"coin"=>$coin,
			"orderno"=>$orderid,
			"type"=>$type,
			"status"=>0,
			"addtime"=>time()
		);

		
		$domain = new Domain_Charge();
		$info = $domain->setOrder($changeid,$orderinfo);
		if(!$info){
			$rs['code']=1001;
			$rs['msg']='订单生成失败';
            return $rs;	
		}else if($info['code']!=0){
            return $info;
		}

			 
		$noceStr = md5(rand(100,1000).time());//获取随机字符串
		$time = time();
			
		$paramarr = array(
			"appid"       =>   $configpri['wx_appid'],
			"body"        =>    "充值{$coin}虚拟币",
			"mch_id"      =>    $configpri['wx_mchid'],
			"nonce_str"   =>    $noceStr,
			"notify_url"  =>    $configpub['site_url'].'/Appapi/pay/notify_wx',
			"out_trade_no"=>    $orderid,
			"total_fee"   =>    $money*100, 
			"trade_type"  =>    "APP"
		);
		$sign = $this -> sign($paramarr,$configpri['wx_key']);//生成签名
		$paramarr['sign'] = $sign;
		$paramXml = "<xml>";
		foreach($paramarr as $k => $v){
			$paramXml .= "<" . $k . ">" . $v . "</" . $k . ">";
		}
		$paramXml .= "</xml>";
			 
		$ch = curl_init ();
		@curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查  
		@curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在  
		@curl_setopt($ch, CURLOPT_URL, "https://api.mch.weixin.qq.com/pay/unifiedorder");
		@curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		@curl_setopt($ch, CURLOPT_POST, 1);
		@curl_setopt($ch, CURLOPT_POSTFIELDS, $paramXml);
		@$resultXmlStr = curl_exec($ch);
		if(curl_errno($ch)){
			//print curl_error($ch);
			file_put_contents('./wxpay.txt',date('y-m-d H:i:s').' 提交参数信息 ch:'.json_encode(curl_error($ch))."\r\n",FILE_APPEND);
		}
		curl_close($ch);

		$result2 = $this->xmlToArray($resultXmlStr);
        
        if($result2['return_code']=='FAIL'){
            $rs['code']=1005;
			$rs['msg']=$result2['return_msg'];
            return $rs;	
        }
		$time2 = time();
		$prepayid = $result2['prepay_id'];
		$sign = "";
		$noceStr = md5(rand(100,1000).time());//获取随机字符串
		$paramarr2 = array(
			"appid"     =>  $configpri['wx_appid'],
			"noncestr"  =>  $noceStr,
			"package"   =>  "Sign=WXPay",
			"partnerid" =>  $configpri['wx_mchid'],
			"prepayid"  =>  $prepayid,
			"timestamp" =>  $time2
		);
		$paramarr2["sign"] = $this -> sign($paramarr2,$configpri['wx_key']);//生成签名
		
		$rs['info'][0]=$paramarr2;
		return $rs;			
	}		
	
	/**
	* sign拼装获取
	*/
	protected function sign($param,$key){
		$sign = "";
		foreach($param as $k => $v){
			$sign .= $k."=".$v."&";
		}
		$sign .= "key=".$key;
		$sign = strtoupper(md5($sign));
		return $sign;
	
	}
	/**
	* xml转为数组
	*/
	protected function xmlToArray($xmlStr){
		$msg = array(); 
		$postStr = $xmlStr; 
		$msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); 
		return $msg;
	}	

		
	/**
	 * 支付宝支付
	 * @desc 用于支付宝支付 获取订单号
	 * @return int code 操作码，0表示成功
	 * @return array info 
	 * @return string info[0].orderid 订单号
	 * @return string msg 提示信息
	 */
	public function getAliOrder() {
		$rs = array('code' => 0, 'msg' => '', 'info' => array());
		
		$uid=$this->uid;
		$changeid=$this->changeid;
		$coin=checkNull($this->coin);
		$money=checkNull($this->money);

		if(!$uid || !$changeid || $coin<=0 || $money<=0){
			$rs['code']=1002;
			$rs['msg']='信息错误';
			return $rs;
		}
        
		$type=1;
		$orderid=$this->getOrderid($uid);
        
		$orderinfo=array(
			"uid"=>$uid,
			"touid"=>$uid,
			"money"=>$money,
			"coin"=>$coin,
			"orderno"=>$orderid,
			"type"=>$type,
			"status"=>0,
			"addtime"=>time()
		);
		
		$domain = new Domain_Charge();

		$info = $domain->setOrder($changeid,$orderinfo);
		if(!$info){
			$rs['code']=1001;
			$rs['msg']='订单生成失败';
            return $rs;	
		}else if($info['code']!=0){
            return $info;
		}
		
		$rs['info'][0]['orderid']=$orderid;
		return $rs;
	}			


}
